package com.icss.th.subjects.facade.mysql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.icss.th.common.config.SystemConfig;
import com.icss.th.common.util.DBUtil;
import com.icss.th.db.sql.SqlText;
import com.icss.th.subjects.facade.ISubjectsFacade;
import com.icss.th.subjects.pojo.Subject;

public class SubjectsFacadeMysql implements ISubjectsFacade 
{
	@Override
	public List<Subject> getChildren(Subject subject) 
	{
		if (subject == null) return null;
		
		List<Subject> list = new ArrayList<Subject>();
		
		Connection conn = DBUtil.getConn();
		
		try
		{
			try
			{
				PreparedStatement ps = conn.prepareStatement(SqlText.GET_CHILDREN_SUBJECTS_SQL);
				ps.setInt(1, subject.getId());
				ps.setInt(2, Integer.valueOf(SystemConfig.SUBJECT_EXAM_COUNT));
				ResultSet rs = ps.executeQuery();
				while (rs.next())
				{
					int id = rs.getInt("id");
					String name = rs.getString("sTitle");
					int level = rs.getInt("depLv");
					list.add(new Subject(id, name, level, subject));
				}
				
				rs.close();
				ps.close();
			}
			finally
			{
				conn.close();
			}
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		
		return list;
	}

	@Override
	public List<Subject> getPopular(int topNum) 
	{
		List<Subject> list = new ArrayList<Subject>();
		
		Connection conn = DBUtil.getConn();
		
		try
		{
			try
			{
				PreparedStatement ps = conn.prepareStatement(SqlText.GET_TOP_N_SUBJECT_SQL);
				ps.setInt(1, topNum);
				ResultSet rs = ps.executeQuery();
				while (rs.next())
				{
					int id = rs.getInt("id");
					String name = rs.getString("sTitle");
					list.add(new Subject(id, name, 2));
				}
				
				rs.close();
				ps.close();
			}
			finally
			{
				conn.close();
			}
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		
		return list;
	}
}
